<?php

// URL重定向
function redirect($url, $time=0, $msg='', $js='') {
  $url = str_replace(array("\n", "\r"), '', $url);
  if($js) {
    $str .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
    $str .= '<script>parent.location.href="'.$url.'";</script>';
    $str .= $msg;
    exit($str);
  }
  if(!headers_sent() && $time==0) {
    header("Location: $url");
    exit;
  }
  else {
    $str  = '<meta http-equiv="Refresh" content="'.$time.';URL='.$url.'" />';
    $str .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
    $str .= $msg;
    exit($str);
  }
}

// array to xml
function array_to_xml($data) {
  if(is_object($data)) {
    $data = get_object_vars($data);
  }
  $xml = '';
  foreach($data as $key=>$val) {
    is_numeric($key) && $key="item id=\"$key\"";
    $xml .= "<$key>";
    $xml .= (is_array($val)||is_object($val)) ? array_to_xml($val) : $val;
    list($key,) = explode(' ',$key);
    $xml .= "</$key>";
  }
  return $xml;
}
function array2xml($data, $encoding='utf-8', $root='root') {
  header('Content-Type: text/xml');
  $xml = '<?xml version="1.0" encoding="'.$encoding.'"?>';
  $xml.= '<'.$root.'>';
  $xml.= array_to_xml($data);
  $xml.= '</'.$root.'>';
  return $xml;
}

//xml to array
function xml_to_array($xml) {
  $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
  if(preg_match_all($reg,$xml,$matches)) {
    $count = count($matches[0]);
    $arr   = array();
    for($i=0;$i<$count;$i++) {
      $key = $matches[1][$i];
      $val = xml_to_array($matches[2][$i]);
      if(array_key_exists($key,$arr)) {
        if(is_array($arr[$key])) {
          if(!array_key_exists(0,$arr[$key])) {
            $arr[$key] = array($arr[$key]);
          }
        }
        else {
          $arr[$key] = array($arr[$key]);
        }
        $arr[$key][] = $val;
      }
      else {
        $arr[$key] = $val;
      }
    }
    return $arr;
  }
  else {
    return $xml;
  }
}
function xml2array($xml) {
  $arr = xml_to_array($xml);
  $key = array_keys($arr);
  return $arr[$key[0]];
}

// 生成随机定长字符
function random($length=6, $chars='0123456789') {
  $hash = '';
  $max = strlen($chars) - 1;
  for($i = 0; $i < $length; $i++) {
    $hash .= $chars[mt_rand(0, $max)];
  }
  return $hash;
}

// 获取文件后缀名
function file_ext($filename) {
  return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

// 文件下载
function file_down($filepath, $filename='') {
  if(!$filename) $filename = basename($filepath);
  $filetype = file_ext($filename);
  $filesize = sprintf("%u", filesize($filepath));
  if(ob_get_length() !== false) @ob_end_clean();
  header('Pragma: public');
  header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
  header('Cache-Control: no-store, no-cache, must-revalidate');
  header('Cache-Control: pre-check=0, post-check=0, max-age=0');
  header('Content-Transfer-Encoding: binary');
  header('Content-Encoding: none');
  header('Content-type: '.$filetype);
  header('Content-Disposition: attachment; filename="'.$filename.'"');
  header('Content-length: '.$filesize);
  readfile($filepath);
  exit;
}

// 获取字符长度
function str_len($str) {
  $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));
  if ($length) {
    return strlen($str) - $length + intval($length / 3) * 2;
  }
  else {
    return strlen($str);
  }
}

// 截取定长字符
function str_sub($str, $length=0, $append=true){
  $str = trim($str);
  $strlength = strlen($str);
  if ($length == 0 || $length >= $strlength) {
    return $str;
  }
  elseif ($length < 0) {
    $length = $strlength + $length;
    if ($length < 0) {
      $length = $strlength;
    }
  }
  
  if (function_exists('mb_substr')) {
    $newstr = mb_substr($str, 0, $length, 'UTF-8');
  }
  elseif (function_exists('iconv_substr')) {
    $newstr = iconv_substr($str, 0, $length, 'UTF-8');
  }
  else {
    $newstr = substr($str, 0, $length);
  }

  if ($append && $str != $newstr) {
    $newstr .= '...';
  }

  return $newstr;
}

// 创建目录
function make_path($path) {
  $dirs = explode('/', dirname($path));
  $tmp = '';
  foreach ($dirs as $dir) {
    $tmp .= $dir . '/';
    if(!file_exists($tmp) && !@mkdir($tmp, 0777)) return $tmp;
  }
  return true;
}

// 创建文件夹
function make_dir($folder) {
  $reval = false;
  if (!file_exists($folder)) {
    @umask(0);
    preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
    $base = ($atmp[0][0] == '/') ? '/' : '';
    foreach ($atmp[1] AS $val) {
      if ('' != $val) {
        $base .= $val;
        if ('..' == $val || '.' == $val) {
          $base .= '/';
          continue;
        }
      }
      else {
        continue;
      }
      $base .= '/';
      if (!file_exists($base)) {
        if (@mkdir(rtrim($base, '/'), 0777)) {
          @chmod($base, 0777);
          $reval = true;
        }
      }
    }
  }
  else {
    $reval = is_dir($folder);
  }
  clearstatcache();
  return $reval;
}

// 删除目录
function del_dir($directory) {
  $mydir = dir($directory);
  while($file = $mydir->read()){
    if((is_dir("$directory/$file")) AND ($file!=".") AND ($file!="..")){
      del_dir("$directory/$file");
    }
    else {
      if(($file!=".") AND ($file!="..")){
        unlink("$directory/$file");
      }
    }
  }
  $mydir->close();
  rmdir($directory);
}

// 目录内容
function list_dir($dir) {
  if(is_dir($dir)) {
    if($handle = opendir($dir)) {
      while(($file = readdir($handle)) !== false) {
        if($file != "." && $file != ".." && $file != "Thumbs.db") {
          echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
        }
      }
      closedir($handle);
    }
  }
}

// 移动文件
function move_file($file_name, $target_name='') {
  if (function_exists("move_uploaded_file")) {
    if (move_uploaded_file($file_name, $target_name)) {
      @chmod($target_name,0755);
      return true;
    }
    elseif (copy($file_name, $target_name)) {
      @chmod($target_name,0755);
      return true;
    }
  }
  elseif (copy($file_name, $target_name)) {
    @chmod($target_name,0755);
    return true;
  }
  return false;
}

// 获取IP
function get_ip() {
  if(getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
    $ip = getenv("HTTP_CLIENT_IP");
  }
  elseif(getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
    $ip = getenv("HTTP_X_FORWARDED_FOR"); 
  }
  elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
    $ip = getenv("REMOTE_ADDR"); 
  }
  elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
    $ip = $_SERVER['REMOTE_ADDR']; 
  }
  else {
    $ip = "0.0.0.0"; 
  }
  return $ip;
}

// 加密解密
function encrypt($str, $key='') {
  if(!defined('AUTH')) {
    define('AUTH', 'fsdkp');
  }
  if(!$key) {$key=AUTH;}
  $coded = '';
  $keylength = strlen($key);
  for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength) {
    $coded .= substr($str, $i, $keylength) ^ $key;
  }
  return str_replace('=', '', base64_encode($coded));
}

function decrypt($str, $key='') {
  if(!defined('AUTH')) {
    define('AUTH', 'fsdkp');
  }
  if(!$key) {$key=AUTH;}
  $coded = '';
  $keylength = strlen($key);
  $str = base64_decode($str);
  for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength) {
    $coded .= substr($str, $i, $keylength) ^ $key;
  }
  return $coded;
}

// 转义特殊字符
function addslashes_deep($value) {
  return $value = is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
}

function stripslashes_deep($value) {
  return $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
}

// URL地址目录(最后无/)  eg. http://localhost/php
function getURL() {
  return strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/'))).'://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
}

// URL带参数的相对地址(以/开始) eg. /php/index.php?module=index
function getURI() {
  return isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : (isset($_SERVER['argv']) ? $_SERVER['PHP_SELF'].'?'.$_SERVER['argv'][0] : $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING']);
}

// URL全地址无参数 eg. http://localhost/php/index.php
function getSURL() {
  return getURL().'/'.basename($_SERVER['PHP_SELF']);
}

// UTF8->GBK
function utf8_gbk($value) {
  return is_array($value) ? array_map('utf8_gbk', $value) : iconv("UTF-8","GBK",$value);
}

// GBK->UTF8
function gbk_utf8($value) {
  return is_array($value) ? array_map('gbk_utf8', $value) : iconv("GBK","UTF-8",$value);
}


// 验证邮箱地址
function email_valid($email, $test_mx=false) {
  if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
    if($test_mx) {
      list($username, $domain) = split("@", $email);
      return getmxrr($domain, $mxrecords);
    }
    else {
      return true;
    }
  }
  else {
    return false;
  }
}

// 压缩
// $files=array('file1.jpg', 'file2.jpg', 'file3.jpg');
// create_zip($files, 'myzipfile.zip', true);
function zip($files=array(),$destination='',$overwrite=false) {
  if(file_exists($destination) && !$overwrite) { return false; }
  $valid_files = array();
  if(is_array($files)) {
    foreach($files as $file) {
      if(file_exists($file)) {
        $valid_files[] = $file;
      }
    }
  }
  if(count($valid_files)) {
    $zip = new ZipArchive();
    if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
      return false;
    }
    foreach($valid_files as $file) {
      $zip->addFile($file,$file);
    }
    $zip->close(); 
    return file_exists($destination);
  }
  else {
    return false;
  }
}

// 解压缩
function unzip($file, $destination) {
  $zip = new ZipArchive() ;
  if ($zip->open($file) !== true) {
    die('Could not open archive');
  }
  if (!$destination) $destination = './';
  $zip->extractTo($destination);
  $zip->close();
}

// 逗号分割的数字还原
function number_deformat($number, $dec_point=null) {
  if(empty($dec_point)) {
    $locale = localeconv();
    $dec_point = $locale['decimal_point'];
  }
  return floatval(str_replace($dec_point, '.', preg_replace('/[^\d'.preg_quote($dec_point).']/', '', $number)));
}

// 匹配汉字 /^[\x{4e00}-\x{9fa5}]+$/u

// 目录大小
function get_dirsize($dir) {
  $handle = opendir($dir);
  while(false!==($FolderOrFile = readdir($handle))) {
    if($FolderOrFile != "." && $FolderOrFile != "..") {
      if(is_dir("$dir/$FolderOrFile")){
        $sizeResult += get_dirsize("$dir/$FolderOrFile");
      }
      else {
        $sizeResult += filesize("$dir/$FolderOrFile");
      }
    }
  }
  closedir($handle);
  return $sizeResult;
}

// 格式化大小
function format_size($size) {
  $kb = 1024;
  $mb = 1024 * $kb; 
  $gb = 1024 * $mb; 
  $tb = 1024 * $gb;
  if($size < $kb) { return $size."B"; }
  else if($size < $mb) { return round($size/$kb,2)."K"; }
  else if($size < $gb) { return round($size/$mb,2)."M"; }
  else if($size < $tb) { return round($size/$gb,2)."G"; }
  else { return round($size/$tb,2)."T"; }
}

// unix时间格式
function set_unixtime($t) {
  return is_numeric($t) ? $t : strtotime($t);
}
  
// dump array
function arr_dump($array, $level=0) {
  $space = '';
  for($i=0; $i<=$level; $i++) {
    $space .= "\t";
  }
  $evaluate = "Array (\n";
  $comma = $space;
  if(is_array($array)) {
    foreach($array as $key => $val) {
      $key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
      $val = !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
      if(is_array($val)) {
        $evaluate .= "$comma$key => " . arr_dump($val, $level + 1);
      }
      else {
        $evaluate .= "$comma$key => $val";
      }
      $comma = ",\n$space";
    }
  }
  if($level==0) {
    $evaluate .= "\n$space);";
  }
  else {
    $evaluate .= "\n$space)";
  }
  return $evaluate;
}


function get_timediff($time1, $time2) {
  $times = abs($time1 - $time2);
  return gmdate('H:i:s', $times);
}



?>